package com.we823.cms.controller.front;

import javax.servlet.http.HttpServletRequest;
import javax.servlet.http.HttpServletResponse;

import org.apache.shiro.SecurityUtils;
import org.apache.shiro.authc.AuthenticationException;
import org.apache.shiro.subject.Subject;
import org.apache.shiro.web.filter.authc.FormAuthenticationFilter;
import org.slf4j.Logger;
import org.slf4j.LoggerFactory;
import org.springframework.stereotype.Controller;
import org.springframework.ui.Model;
import org.springframework.web.bind.annotation.RequestMapping;
import org.springframework.web.bind.annotation.RequestMethod;

import com.we823.cms.common.WebConstants;
import com.we823.cms.common.utils.RequestUtil;
import com.we823.cms.common.web.FrontUtils;

@Controller
public class LoginController {

	private String baseUrl = WebConstants.WEB_TEMPLATE_PREFIX;
	
	private Logger logger = LoggerFactory.getLogger(LoginController.class);
	
	@RequestMapping(value="login",method=RequestMethod.GET)
	public String login(HttpServletRequest request,Model model){
		logger.debug("login get...");
		
		int notfound=RequestUtil.getValueByName(request, "nofound", 0);
		int logout = RequestUtil.getValueByName(request, "logout", 0);
		int blocked = RequestUtil.getValueByName(request, "blocked", 0);
		int unknown = RequestUtil.getValueByName(request, "unknown", 0);
		
		boolean hasError = false;
		String message = "";
		if(notfound==1) {
			hasError=true;
			message = "用户名密码错误！";
		}
		if(logout==1) {
			hasError=true;
			message="你已成功退出系统";
		}
		if(blocked==1) {
			hasError=true;
			message="帐号被锁定了，无法进入系统";
		}
		if(unknown==1) {
			hasError=true;
			message="发生未知错误，无法进入系统";
		}
		AuthenticationException ae = (AuthenticationException) request.getAttribute(FormAuthenticationFilter.DEFAULT_ERROR_KEY_ATTRIBUTE_NAME);
		if(ae!=null) {
			hasError = true;
			message = "用户名或密码错误，无法进入系统";
		}
		model.addAttribute("hasError",hasError);
		model.addAttribute("message",message);
		
		//如果用户直接到登录页面 先退出一下
        //原因：isAccessAllowed实现是subject.isAuthenticated()---->即如果用户验证通过 就允许访问
        // 这样会导致登录一直死循环
        
		Subject subject = SecurityUtils.getSubject();
        if (subject != null) {
        	if(subject.isAuthenticated()) {
        		subject.logout();
        	}
        }
        
		return FrontUtils.buildTemplateUrl(baseUrl, "login");
	}
	
	@RequestMapping(value="login",method=RequestMethod.POST)
	public String login(Model model,HttpServletRequest request,HttpServletResponse response){
		logger.debug("login post...");
		return FrontUtils.buildTemplateUrl(baseUrl, "login");
	}
}
